#include "publisherview.h"
#include <iostream>

PublisherView::PublisherView():mydoc(0)
{
    //Create the Tree model:
    refTreeModel = Gtk::ListStore::create(columns);
    set_model(refTreeModel);

    //Add the TreeView's view columns:
    column.set_title("Publisher");
    column.pack_start(cellrenderer);
    column.set_resizable(true);
    append_column(column);
    //append_column("Count",columns.count);
    column.set_cell_data_func(cellrenderer, sigc::mem_fun(*this, &PublisherView::datarender) );
    set_headers_visible(false);

    signal_row_activated().connect(sigc::mem_fun(*this,&PublisherView::select));
    signal_drag_data_received().connect(sigc::mem_fun(*this,&PublisherView::drag_data_received) );
    std::vector<Gtk::TargetEntry> targets;
    targets.push_back( Gtk::TargetEntry("PUBLISHER-ID") );
    drag_source_set(targets);
    targets.push_back( Gtk::TargetEntry("DOCUMENT-ID") );
    drag_dest_set(targets);
    enable_model_drag_dest(targets);
    get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
    signal_drag_data_get().connect(sigc::mem_fun(*this,&PublisherView::onDataGet));
}

PublisherView::~PublisherView()
{
}
void PublisherView::set_documents(sdms::documents* doc)
{
    mydoc=doc;
}

void PublisherView::update()
{
    if (!mydoc) return;
    std::vector<sdms::publisher> t=mydoc->getpublisher();
    refTreeModel->clear();
    for(int i=0; i<t.size(); i++)
    {
        Gtk::TreeModel::Row row = *(refTreeModel->append());
        row[columns.name] =  t[i].name;
        //row[columns.count] =  t[i].count;
    }
}
void PublisherView::viewbookitem()
{
    if (!mydoc) return;
    std::vector<sdms::publisher> t=mydoc->bookpublisher();
    refTreeModel->clear();
    for(int i=0; i<t.size(); i++)
    {
        Gtk::TreeModel::Row row = *(refTreeModel->append());
        row[columns.name] =  t[i].name;
        //row[columns.count] =  t[i].count;
    }
}
void PublisherView::viewarticleitem()
{
    if (!mydoc) return;
    std::vector<sdms::publisher> t=mydoc->articlepublisher();
    refTreeModel->clear();
    for(int i=0; i<t.size(); i++)
    {
        Gtk::TreeModel::Row row = *(refTreeModel->append());
        row[columns.name] =  t[i].name;
        //row[columns.count] =  t[i].count;
    }
}
void PublisherView::viewnopdfitem()
{
    if (!mydoc) return;
    std::vector<sdms::publisher> t=mydoc->nopdfpublisher();
    refTreeModel->clear();
    for(int i=0; i<t.size(); i++)
    {
        Gtk::TreeModel::Row row = *(refTreeModel->append());
        row[columns.name] =  t[i].name;
        //row[columns.count] =  t[i].count;
    }
}

//处理弹出菜单
bool PublisherView::on_button_press_event(GdkEventButton* event)
{
    //Call base class, to allow normal handling,
    //such as allowing the row to be selected by the right-click:
    bool return_value = TreeView::on_button_press_event(event);

    //Then do our custom stuff:
    if( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) )
    {
        //menuPopup.popup(event->button, event->time);
    }
    return return_value;
}

void PublisherView::datarender(Gtk::CellRenderer* /* renderer */, const Gtk::TreeModel::iterator& iter)
{
    //Get the value from the model and show it appropriately in the view:
    if(iter)
    {
        Gtk::TreeModel::Row row = *iter;
        //std::string model_value = row[columns.name];
        cellrenderer.property_text() = row[columns.name];
    }
}

void PublisherView::drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
                                       const Gtk::SelectionData& selection_data, guint, guint time)
{
    if (selection_data.get_data_type()=="DOCUMENT-ID")
    {
        std::string sel=selection_data.get_data_as_string();
        Gtk::TreeModel::Path path;
        Gtk::TreeViewDropPosition  pos;
        get_dest_row_at_pos(x,y,path,pos);
        Gtk::TreeModel::iterator  iter = refTreeModel->get_iter(path);
        std::vector<std::string> singledoc=utils::explode(sel,",");
        sdms::publisher t;
        //t.name=(*iter)[columns.name];
        for (int i=0; i<singledoc.size(); i++)
        {
            sdms::document d;
            //d.id=utils::fromString<int>(singledoc[i]);
            //if (mydoc->update(&t,&d))  (*iter)[columns.count]=t.count;
        }
    }
    context->drag_finish(false, false, time);
}

//调用主界面的窗口，增加过滤器
void PublisherView::select(const Gtk::ListStore::Path& path, Gtk::TreeViewColumn* column)
{
    //判断当前编辑状态
    //std::cout << "Test select function." << std::endl;
    Glib::RefPtr<Gtk::TreeView::Selection> refSelection = get_selection();
    if(refSelection)
    {
        //Gtk::TreeModel::iterator iter = refSelection->get_selected();
        std::list<Gtk::TreeModel::Path> selected = refSelection->get_selected_rows();
        //双击或回车应该只有一个要素
        //for(std::list<Gtk::TreeModel::Path>::iterator i=selected.begin();i!=selected.end();i++)
        Gtk::TreeModel::iterator iter = refTreeModel->get_iter(*(selected.begin()));
        if(iter && filterview)
        {
            sdms::PublisherFilter tf;
            tf.set_documents(mydoc);
            //std::cout<<(*iter)[columns.name]<<std::endl;
            Glib::ustring name=(*iter)[columns.name];
            tf.set_name(name);
            tf.eval();
            filterview->clear();
            filterview->add(tf);
            //docview->update(&tf);
        }
    }
}
void PublisherView::set_docview(DocView* dv)
{
    docview=dv;
}
void PublisherView::set_filterview(FilterView* fv)
{
    filterview=fv;
}
void PublisherView::onDataGet(const Glib::RefPtr<Gdk::DragContext>&,   Gtk::SelectionData& selection_data, guint, guint)
{
    std::string id;
    Glib::RefPtr<Gtk::TreeView::Selection> refSelection = get_selection();
    if(refSelection)
    {
        std::list<Gtk::TreeModel::Path> selected = refSelection->get_selected_rows();
        //默认的多选拖动行为不够友好
        //是否需要自己进一步处理？
        //std::cout<<selected.size()<<std::endl;
        for(std::list<Gtk::TreeModel::Path>::iterator i=selected.begin(); i!=selected.end(); i++)
        {
            Gtk::TreeModel::iterator iter = refTreeModel->get_iter(*i);
            Gtk::TreeModel::Row row = *iter;
            if (i!=selected.begin()) id+=",";
            Glib::ustring s=row[columns.name];
            id+=s;
        }
        selection_data.set(selection_data.get_target(), 8 /* 8 bits format */,
                           (const guchar*)id.c_str(),id.size());

    }
}
